import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {ActivatedRoute, Router} from '@angular/router';
import {Observable, throwError} from 'rxjs';
import {catchError, retry, tap} from 'rxjs/operators';
import {Zero3LayoutNavbarComponent} from '../zero3-layout-navbar/zero3-layout-navbar.component';
import {Injectable} from '@angular/core';
import {Zero3AlertLg} from '../global/zero3-alert-lg/zero3-alert-lg.component';
import {isNullOrUndefined} from 'util';
import {Zero3Alert} from '../global/zero3-alert/zero3-alert.component';

@Injectable()
export class HttpRequestClient {

    static http: HttpClient;
    static router: Router;
    static route: ActivatedRoute;


    constructor(private http: HttpClient, private router: Router, private route: ActivatedRoute) {
        HttpRequestClient.http = http;
        HttpRequestClient.router = router;
        HttpRequestClient.route = route;
    }

    static GET(url): Observable<any> {
        // debugger;
        const headers: HttpHeaders = new HttpHeaders(
            {'authorization': localStorage.getItem('loginToken') || ''}
        );
        // headers.set('authorization', localStorage.getItem('loginToken'));
        return HttpRequestClient.http.get(url, {headers: headers}).pipe(
            retry(3),
            tap(
                // Succeeds when there is a response; ignore other events
                event => {
                    console.log('success');
                    Zero3LayoutNavbarComponent.RES_STATUS = 200;
                },
                // Operation failed; error is an HttpErrorResponse
                error => {
                    console.log('fail');
                    Zero3LayoutNavbarComponent.RES_STATUS = 400;
                }
            ),
            catchError(HttpRequestClient.handleError),
        );
    }

    static POST(url, domain, callback: {success: (result) => void, error: (result) => void}): Observable<any> {
        const headers = new HttpHeaders({
                'authorization': localStorage.getItem('loginToken') || '',
                'Content-Type': 'application/json;charset=UTF-8'
            });
        const httpOptions = {
            headers: headers
        };
        // domain.uuid = 'uuid';
        return HttpRequestClient.http.post(url, domain, httpOptions).pipe(
            tap(
                // Succeeds when there is a response; ignore other events
                event => {
                    console.log('success');
                    Zero3LayoutNavbarComponent.RES_STATUS = 200;
                    callback.success(event);
                },
                // Operation failed; error is an HttpErrorResponse
                error => {
                    console.log('fail');
                    Zero3LayoutNavbarComponent.RES_STATUS = 400;
                    callback.error(error);
                }
            ),
            catchError(HttpRequestClient.handleError),
        );
    }

    static PUT(url, domain, callback: {success: (result) => void, error: (result) => void}): Observable<any> {
        console.log(url);
        console.log(domain);
        const headers = new HttpHeaders({
            'authorization': localStorage.getItem('loginToken') || '',
            'Content-Type': 'application/json;charset=UTF-8'
        });
        const httpOptions = {
            headers: headers
        };
        return HttpRequestClient.http.put(url, domain, httpOptions).pipe(
            tap(
                // Succeeds when there is a response; ignore other events
                event => {
                    console.log('success');
                    Zero3LayoutNavbarComponent.RES_STATUS = 200;
                    callback.success(event);
                },
                // Operation failed; error is an HttpErrorResponse
                error => {
                    console.log('fail');
                    console.log(error);
                    Zero3LayoutNavbarComponent.RES_STATUS = 400;
                    callback.error(error);
                }
            ),
            catchError(HttpRequestClient.handleError),
        );
    }

    static handleError(error: HttpErrorResponse) {
        //
        if (error.error instanceof ErrorEvent) {
            // A client-side or network error occurred. Handle it accordingly.
            console.error('An error occurred:', error.error.message);
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            console.error(
                `Backend returned code ${error.status}, ` +
                `body was: ${error.error}`);
        }
        if (error.error && error.error.status === 401) {
            HttpRequestClient.router.navigate(['/login']);
        } else if (error.error && error.error.status === 403) {
            Zero3Alert.req('您没有权限操作');
        }
        //
        console.log(error);
        //
        if (isNullOrUndefined(error.error) || isNullOrUndefined(error.error)) {
            Zero3AlertLg.setMessage(JSON.stringify(error));
        } else {
            Zero3AlertLg.setMessage(JSON.stringify(error.error));
        }
        // return an observable with a user-facing error message
        return throwError(
            'Something bad happened; please try again later.');
    }

}
